import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Passenger } from './passenger';
import { SERVER} from '../../app.config';

@Injectable()
export class PassengerService {
    constructor(private http: Http){

    }

    getPassengers(): Promise<Passenger[]> {
        //这里需要修改成passenger的url
        return this.http.get(SERVER.PASSENGER)
        .toPromise()
        .then(response => response.json() as Passenger[])
        .catch(this.handleError);
    }

    getPassenger(passenger_id: string) {
        return this.getPassengers()
            .then(passengers => passengers.find(passenger => passenger.passenger_id ===passenger_id ));
    }

    searchPassengers(passenger_id: string, passenger_name: string): Promise<Passenger[]> {
        //+ '&end_time=' + end_time

        if(typeof(passenger_id)=="undefined"){
            passenger_id = ""; 
        }
        if(typeof(passenger_name)=="undefined"){
            passenger_name = "";
        }
        let url = SERVER.PASSENGER + "/find?passenger_id="+passenger_id+'&passenger_name=' + passenger_name ; 
        return this.http.get(url)
        .toPromise()
        .then(response => response.json() as Passenger[])
        .catch(this.handleError); 
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(passenger: Passenger): Promise<Passenger> {
        let headers = new Headers({
            'Content-type': 'application/json'});
        //这里需要修改成passenger的增加url
        return this.http.post(SERVER.PASSENGER, JSON.stringify(passenger), {headers: headers})
        .toPromise()
        // .then(res => res.json().data)
        .then(() => passenger)
        .catch(this.handleError);
    }

    //更新
    private put(passenger: Passenger): Promise<Passenger> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.PASSENGER}` + '/' + passenger.passenger_id;

        return this.http.put(url, JSON.stringify(passenger), {headers: headers})
                   .toPromise()
                   .then(() => passenger)
                   .catch(this.handleError);
    }

    //删除
    // delete(driver: Driver): Promise<Response> {
    //     let headers = new Headers();
    //     headers.append('Content-Type', 'application/json');

    //     let url = `${SERVER.DRIVER}/${driver.driver_id}`;

    //     return this.http
    //                .delete(url, { headers: headers})
    //                .toPromise()
    //                .catch(this.handleError);
    // }

    //保存
    save(passenger: Passenger): Promise<Passenger> {
        if (passenger.passenger_id) {
            return this.put(passenger)
        }
        return this.post(passenger);
    }
}